package com.zy.fee.roadpark.activity.np;

import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.inputmethodservice.Keyboard;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.flyco.roundview.RoundTextView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.shouzhong.scanner.ScannerUtils;
import com.zy.fee.roadpark.R;
import com.zy.fee.roadpark.config.Constants;
import com.zy.fee.roadpark.dao.FileLogic;
import com.zy.fee.roadpark.dao.NpNodeLogic;
import com.zy.fee.roadpark.dao.NpNodeRecordLogic;
import com.zy.fee.roadpark.util.Printer;
import com.zy.fee.roadpark.view.CommonDialog;
import com.zygk.library.base.BaseActivity;
import com.zygk.library.model.CommonResult;
import com.zygk.library.util.ColorUtil;
import com.zygk.library.util.DateTimeUtil;
import com.zygk.library.util.FileUtil;
import com.zygk.library.util.HttpRequest;
import com.zygk.library.util.ImageUtil;
import com.zygk.library.util.PreferencesHelper;
import com.zygk.library.util.StringUtils;
import com.zygk.library.util.ToastUtil;
import com.zygk.library.view.XKeyboardView;
import com.zygk.library.view.gridpasswordview.GridPasswordView;
import java.util.ArrayList;

import static com.printer.sdk.PrinterConstants.BarcodeType.DATAMATRIX;
import static com.printer.sdk.PrinterConstants.BarcodeType.PDF417;

/**
 * Created by Wikison on 2019/3/28. 登记车牌
 */
public class NpRegistrationPlateActivity extends BaseActivity {

  @BindView(R.id.lh_tv_title) TextView lhTvTitle;
  @BindView(R.id.et_code) EditText etCode;
  @BindView(R.id.gpvPlateNumber) GridPasswordView gpvPlateNumber;
  @BindView(R.id.view) View view;
  @BindView(R.id.view_keyboard) XKeyboardView viewKeyboard;
  @BindView(R.id.tv_button) RoundTextView tvButton;

  private ArrayList<ImageItem> images = null;
  private String plateNumber;
  private String printTime;
  private double payMoney = 0;
  private String nodeRecordID = "";
  private String code = "";

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ButterKnife.bind(this);
  }

  @Override public void setContentView() {
    setContentView(R.layout.activity_np_registration_plate);
  }

  @Override public void init() {
    registerReceiver(new String[] { Constants.BROADCAST_FORENSICS_SUCCESS });

    initData();
    initView();
    initListener();
  }

  private void initData() {
    initImagePickerSingle(false);
  }

  private void initView() {
    lhTvTitle.setText("打印小票");
    tvButton.setEnabled(false);
  }

  private void initListener() {
    viewKeyboard.setIOnKeyboardListener(new XKeyboardView.IOnKeyboardListener() {
      @Override public void onInsertKeyEvent(String text) {
        gpvPlateNumber.appendPassword(text);
      }

      @Override public void onDeleteKeyEvent() {
        gpvPlateNumber.deletePassword();
      }
    });

    gpvPlateNumber.togglePasswordVisibility();

    gpvPlateNumber.setOnPasswordChangedListener(new GridPasswordView.OnPasswordChangedListener() {
      @Override public boolean beforeInput(int position) {
        if (position == 0) {
          viewKeyboard.setKeyboard(new Keyboard(mContext, R.xml.provice));
          viewKeyboard.setVisibility(View.VISIBLE);
          return true;
        } else if (position >= 1 && position < 2) {
          viewKeyboard.setKeyboard(new Keyboard(mContext, R.xml.english));
          viewKeyboard.setVisibility(View.VISIBLE);
          return true;
        } else if (position >= 2 && position <= 7) {
          viewKeyboard.setKeyboard(new Keyboard(mContext, R.xml.qwerty_without_chinese));
          viewKeyboard.setVisibility(View.VISIBLE);
          return true;
        }
        viewKeyboard.setVisibility(View.GONE);
        return false;
      }

      @Override public void onTextChanged(String psw) {
        if (psw.replace(" ", "").length() >= 7) {
          tvButton.getDelegate()
              .setBackgroundColor(ColorUtil.getColor(mContext, R.color.theme_color));
          tvButton.setEnabled(true);
        } else {
          tvButton.getDelegate()
              .setBackgroundColor(ColorUtil.getColor(mContext, R.color.font_black_999));
          tvButton.setEnabled(false);
        }
      }

      @Override public void onInputFinish(String psw) {
      }
    });

    view.setOnClickListener(v -> viewKeyboard.setVisibility(View.GONE));

    gpvPlateNumber.setOnFocusChangeListener((v, hasFocus) -> {
      if (!hasFocus) {
        viewKeyboard.setVisibility(View.GONE);
      }
    });

    etCode.setOnFocusChangeListener((view, hasFocus) -> {
      if (hasFocus) {
        viewKeyboard.setVisibility(View.GONE);
      } else {
        InputMethodManager imm =
            (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
      }
    });
  }

  private void printNoPaper() {
    CommonDialog.showYesDialog(mContext, "缺纸提示", "设备无纸，小票未打印！\n是否继续登记？", "继续登记", () -> {
      Intent intent = new Intent(mContext, NpForensicsActivity.class);
      intent.putExtra(NpForensicsActivity.INTENT_PLATE_NUMBER, plateNumber);
      intent.putExtra(NpForensicsActivity.INTENT_NODE_RECORD_ID, nodeRecordID);
      startActivity(intent);
      finish();
    });
  }

  private void printTicket() {
    if (StringUtils.isBlank(nodeRecordID)) {
      ToastUtil.showMessage(mContext, "请稍后重试");
      return;
    }
    tvButton.getDelegate().setBackgroundColor(ColorUtil.getColor(mContext, R.color.font_black_999));
    tvButton.setEnabled(false);
    try {
      Printer.printT(plateNumber, printTime, Constants.PAY_NP_URL + nodeRecordID, true, preferencesHelper.getSettingString(PreferencesHelper.User.Key.LOT_ID));

      Intent intent = new Intent(mContext, NpForensicsActivity.class);
      intent.putExtra(NpForensicsActivity.INTENT_PLATE_NUMBER, plateNumber);
      intent.putExtra(NpForensicsActivity.INTENT_CODE, code);
      intent.putExtra(NpForensicsActivity.INTENT_NODE_RECORD_ID, nodeRecordID);
      startActivity(intent);
      finish();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
      //添加图片返回
      if (data != null && requestCode == REQUEST_CODE_SELECT) {
//        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
//        String path = images.get(0).path;
//        String plate = "";
//        try {
//          plate = ScannerUtils.decodeLicensePlate(mContext,
//              ImageUtil.createImageThumbnail(path, 200 * 1024));
//        } catch (Exception e) {
//          e.printStackTrace();
//        }
//        if (StringUtils.isBlank(plate)) {
//          ocr_vehicle_plate(path);
//        } else {
//          ToastUtil.showMessage(mContext, "识别成功。");
//          gpvPlateNumber.setPassword(plate);
//          tvButton.getDelegate()
//              .setBackgroundColor(ColorUtil.getColor(mContext, R.color.theme_color));
//          tvButton.setEnabled(true);
//          FileUtil.deleteSingleFile(path);
//          FileUtil.deletePicture(mContext, path);
//        }
        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
        String path = images.get(0).path;
        ocr_vehicle_plate(path);
      }
    }
  }

  private BitmapFactory.Options getBitmapOption(int inSampleSize) {
    System.gc();
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPurgeable = true;
    options.inSampleSize = inSampleSize;
    return options;
  }

  /**
   * 车牌识别
   */
  private void ocr_vehicle_plate(String path) {
    FileLogic.GetCPSB(mContext, path, new HttpRequest.HttpCallback() {
      @Override public void onStart() {
        showPd();
      }

      @Override public void onSucceed(Object obj) {
        String plateNum = (String) obj;
        if (!StringUtils.isBlank(plateNum) && (plateNum.length() == 7 || plateNum.length() == 8)) {
          gpvPlateNumber.setPassword(plateNum);
          tvButton.getDelegate()
              .setBackgroundColor(ColorUtil.getColor(mContext, R.color.theme_color));
          tvButton.setEnabled(true);
          FileUtil.deleteSingleFile(path);
          FileUtil.deletePicture(mContext, path);
        } else {
          ToastUtil.showMessage(mContext, "识别出的车牌号有误");
        }
      }

      @Override public void onFailed() {
        ToastUtil.showMessage(mContext, "识别失败，请重新识别或手动输入");
      }

      @Override public void onFinish() {
        dismissPd();
      }
    });
  }

  @OnClick({
      R.id.ll_back, R.id.iv_scan, R.id.tv_button
  }) public void onViewClicked(View view) {
    Intent intent;
    switch (view.getId()) {
      case R.id.ll_back:
        finish();
        break;
      case R.id.iv_scan:
        picOne();
        break;
      case R.id.tv_button:
        code = etCode.getText().toString();
        plateNumber = gpvPlateNumber.getPassWord();
        if (!StringUtils.isBlank(plateNumber)) {
          npnode_whether_escape();
        } else {
          if (StringUtils.isBlank(plateNumber)) {
            ToastUtil.showMessage(mContext, "请输入车牌号");
          }
        }
        break;
    }
  }

  private void npnode_whether_escape() {
    NpNodeRecordLogic.npnode_whether_escape(mContext, plateNumber, new HttpRequest.HttpCallback() {
      @Override public void onStart() {
        showPd();
      }

      @Override public void onSucceed(Object obj) {
        CommonResult result = (CommonResult) obj;
        if (result.getEscape() == 1) {
          CommonDialog.showYesOrNoWithTitleDialog(mContext, "追缴提示", plateNumber + "有历史未缴费单据需追缴",
              "继续登记", "打开追缴页面", () -> {
                Intent intent = new Intent(mContext, NpOverpayBillListActivity.class);
                intent.putExtra(NpOverpayBillListActivity.INTENT_PLATE_NUMBER, plateNumber);
                startActivity(intent);
              }, () -> {
                getNodeRecordID();
              });
        } else {
          getNodeRecordID();
        }
      }

      @Override public void onFailed() {

      }

      @Override public void onFinish() {
        dismissPd();
      }
    });
  }

  private void getNodeRecordID() {
    NpNodeRecordLogic.npnode_get_node_record_id(mContext,
        preferencesHelper.getSettingString(PreferencesHelper.User.Key.LOT_ID), plateNumber,
        new HttpRequest.HttpCallback() {
          @Override public void onStart() {

          }

          @Override public void onSucceed(Object obj) {
            CommonResult result = (CommonResult) obj;
            if (result.getStatus() == 1) {
              ToastUtil.showMessage(mContext, "该车在停车场已登记!");
            } else {
              create_node_Record();
            }
          }

          @Override public void onFailed() {

          }

          @Override public void onFinish() {

          }
        });
  }

  private void create_node_Record() {
    printTime = DateTimeUtil.getCurrentTime();

    NpNodeLogic.create_node_Record(mContext, preferencesHelper.userManager().getUserID(),
        preferencesHelper.getSettingString(PreferencesHelper.User.Key.LOT_ID), plateNumber,
        printTime, payMoney, code, new HttpRequest.HttpCallback() {
          @Override public void onStart() {
            showNoCancelPd();
          }

          @Override public void onSucceed(Object obj) {
            //ToastUtil.showMessage(mContext, "车辆登记成功！");
            CommonResult result = (CommonResult) obj;
            sendBroadcast(new Intent(Constants.BROADCAST_FORENSICS_SUCCESS));
            nodeRecordID = result.getNodeRecordID();
            printTicket();
          }

          @Override public void onFailed() {

          }

          @Override public void onFinish() {
            dismissPd();
          }
        });
  }
}
